//
//  String.swift
//
//  Created by 董振山 on 2018/4/17.
//  Copyright © 2018年 董振山. All rights reserved.
//

import Foundation
import UIKit
import CommonCrypto
//MARK: 常用处理
extension String {
    
    /// 是否为NULL
   public func isNil() -> Bool{
        if self == "" || self.count == 0 {
            return true
        }
        return false
    }
    

    
    /// 截取index之后的字符串(包含index)
    public func cc_subString(from index: Int) -> String{
        if self.count > index {
            let startIndex = self.index(self.startIndex, offsetBy: index)
            let substring = self[startIndex..<self.endIndex]
            return String(substring)
        } else {
            return self
        }
    }
    /// 截取index之前的字符串（不包含index）
    public func cc_subString(to index: Int) -> String{
        if self.count > index {
            let endIndex = self.index(self.startIndex, offsetBy: index)
            let substring = self[self.startIndex..<endIndex]
            return String(substring)
        } else {
            return self
        }
    }
    
    /// 截取范围内的字符串(左右都包含)
    public func cc_substring(from index1: Int , to index2: Int) -> String{
        if self.count > index1 && self.count > index2 {
            let startIndex = self.index(self.startIndex, offsetBy: index1)
            let endIndex = self.index(self.startIndex, offsetBy: index2)
            let substring = self[startIndex...endIndex]
            return String(substring)
        } else {
            return self
        }
    }
}


// MARK:String 文件的目录
extension String{
    
    ///   get cache dir
   public func cacheDir()->String{
        let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as NSString
        return path.appendingPathComponent((self as NSString).lastPathComponent)
    }
    
    ///   get document dir
   public func docDir()->String{
        let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as NSString
        return path.appendingPathComponent((self as NSString).lastPathComponent)
    }
    
    ///   get temporary dir
   public func tempDir()->String{
        let path = NSTemporaryDirectory() as NSString
        return path.appendingPathComponent((self as NSString).lastPathComponent)
    }
}


//MARK: 加密与编码
extension String{
    /// sha1 加密
    func sha1() -> String {
        //UnsafeRawPointer
        let data = self.data(using: String.Encoding.utf8)!
        var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH))
        
        let newData = NSData.init(data: data)
        CC_SHA1(newData.bytes, CC_LONG(data.count), &digest)
        let output = NSMutableString(capacity: Int(CC_SHA1_DIGEST_LENGTH))
        for byte in digest {
            output.appendFormat("%02x", byte)
        }
        return output as String
    }
    
    /// md5 加密
    func md5() -> String{
        let cStr = self.cString(using: String.Encoding.utf8);
        let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 16)
        CC_MD5(cStr!,(CC_LONG)(strlen(cStr!)), buffer)
        let md5String = NSMutableString();
        for i in 0 ..< 16{
            md5String.appendFormat("%02x", buffer[i])
        }
        free(buffer)
        return md5String as String
    }
    
    
    /// url编码
    public mutating func urlEncode() {
        if let encoded = addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
            self = encoded
        }
    }
    /// url解码
    public mutating func urlDecode() {
        if let decoded = removingPercentEncoding {
            self = decoded
        }
    }
    
    /// base64 解码
    public var base64Decoded: String? {
        guard let decodedData = Data(base64Encoded: self) else { return nil }
        return String(data: decodedData, encoding: .utf8)
    }
    
    /// base64 编码
    public var base64Encoded: String? {
        let plainData = data(using: .utf8)
        return plainData?.base64EncodedString()
    }
}

//MARK: 文字计算
extension String{
    //    获取文字宽度
    func get_widthForComment(font: UIFont, height: CGFloat = 15) -> CGFloat {
        let rect = NSString(string: self).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: height), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
        return ceil(rect.width)
    }
    
    //    获取文字高度
    func get_heightForComment(font: UIFont, width: CGFloat) -> CGFloat {
        let rect = NSString(string: self).boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
        return ceil(rect.height)
    }
}

extension String{
    /// 删除线
    public var strikethrough: NSAttributedString {
        return NSAttributedString(string: self, attributes: [.strikethroughStyle: NSNumber(value: NSUnderlineStyle.single.rawValue as Int)])
    }
}

